import React, { useEffect, useRef, useState } from 'react'
import { Modal, Button, message, Spin } from 'antd'
import { faceService } from '../../services/face'

type Props = {
    open: boolean
    onClose: () => void
    onSuccess: (userId: string) => void
}

const FaceLoginModal: React.FC<Props> = ({ open, onClose, onSuccess }) => {
    const videoRef = useRef<HTMLVideoElement | null>(null)
    const streamRef = useRef<MediaStream | null>(null)
    const [busy, setBusy] = useState(false)
    const [cameraReady, setCameraReady] = useState(false)
// 摄像头初始化
    useEffect(() => {
        const start = async () => {
            if (!open) return
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480 }, audio: false })
                streamRef.current = stream
                if (videoRef.current) {
                    videoRef.current.srcObject = stream
                    await videoRef.current.play()
                    setCameraReady(true)
                }
            } catch (e) {
                message.error('无法访问摄像头，请检查浏览器权限')
                onClose()
            }
        }
        start()
        return () => {
            if (streamRef.current) {
                streamRef.current.getTracks().forEach(t => t.stop())
                streamRef.current = null
            }
            setCameraReady(false)
        }
    }, [open, onClose])
 // 图像捕获
    const captureBase64 = (): string => {
        const video = videoRef.current!
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth || 640
        canvas.height = video.videoHeight || 480
        const ctx = canvas.getContext('2d')!
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        const dataUrl = canvas.toDataURL('image/jpeg', 0.9)
        return dataUrl.replace(/^data:image\/\w+;base64,/, '')
    }
// 人脸识别处理
    const handleRecognize = async () => {
        if (!cameraReady) {
            message.warning('摄像头未就绪，请稍后再试')
            return
        }
        setBusy(true)
        const hide = message.loading({ content: '正在识别，请稍候...', key: 'face_recog', duration: 0 })
        try {
            message.loading({ content: '正在获取授权...', key: 'face_step', duration: 0 })
            const base64 = captureBase64()
            const token = await faceService.getAccessToken()
            message.loading({ content: '正在进行人脸检测...', key: 'face_step', duration: 0 })
            // 可选：质量/活体检测
            await faceService.detectFace(base64, token)
            message.loading({ content: '正在搜索人脸库...', key: 'face_step', duration: 0 })
            const hit = await faceService.multiSearch(base64, token)
            if (hit && hit.score >= 80) {
                message.success({ content: '人脸识别通过', key: 'face_step' })
                onSuccess(hit.userId || 'face_user')
            } else {
                message.error({ content: '未匹配到已注册人脸或分数过低', key: 'face_step' })
            }
        } catch (e: any) {
            const errMsg = e?.response?.data?.error_msg || e?.message || '识别失败，请重试'
            message.error({ content: errMsg, key: 'face_step' })
        } finally {
            hide()
            setBusy(false)
        }
    }

    return (
        <Modal open={open} onCancel={onClose} footer={null} width={720} title="人脸识别登录">
            <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
                <video ref={videoRef} style={{ width: 640, height: 480, background: '#000', borderRadius: 6 }} />
                {busy && <Spin />}
            </div>
            <div style={{ marginTop: 16, display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
                <Button onClick={onClose}>取消</Button>
                <Button type="primary" onClick={handleRecognize} loading={busy} disabled={!cameraReady}>开始识别</Button>
            </div>
        </Modal>
    )
}

export default FaceLoginModal



